﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools
{
    public partial class BoxCodePrint : Form
    {
        HttpAgreement http;
        cMethods.DBHelper db;
        string boxType = "";
        string lType = "xm"; 
        public BoxCodePrint(string bType)
        {
            InitializeComponent();
            http = new HttpAgreement();
            db = new DBHelper();
            boxType = bType;
        }

        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void BoxCodePrint_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "箱码打印";
                loadPrintTemplte();
                PrintDocument fPrintDocument = new PrintDocument(); //获取默认打印机的方法
                cbPrint.Text = fPrintDocument.PrinterSettings.PrinterName;
                tbNumber.Text = "1";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void VisitService()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["printNum"] = tbPrintNum.Text;
            dic["capacity"] =tbNumber.Text;
            dic["types"] = boxType ;
            dic["createuser"] = CommonMethods.userCode;
            var msg = http.PostJson("SaveBoxBarCode", JsonConvert.SerializeObject(dic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                    {
                        MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    var table = this.printTable();
                    var arr = json["Data"].ToString().Split(',');
                    for (int i = 0; i < arr.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(arr[i]))
                        {
                            table.Rows[i]["barCode"] = arr[i];
                        }
                    }
                    DoPrint(table);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //创建打印表
        private DataTable createPrintTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("proCodes");//箱装存货
            dt.Columns.Add("barCode");
            dt.Columns.Add("capacity");//箱容量
                   
            return dt;
        }
        /// <summary>
        /// 打印模板
        /// </summary>
        private void loadPrintTemplte()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select lbCode,lbName from bar_PrintTemplates_list where status=1");
            sb.Append(" and lType='" + lType + "'");
            var table = db.getData(sb.ToString(), "");
            cbTemplate.DataSource = table;
            cbTemplate.ValueMember = "lbCode";
            cbTemplate.DisplayMember = "lbName";
        }

        //赋值
        private DataTable printTable()
        {
            var table = createPrintTable();
            for (int i = 0; i < int.Parse(tbPrintNum.Text); i++)
            {
                DataRow r = table.NewRow();
                r["proCodes"] = i.ToString();
                r["capacity"] = tbNumber.Text;//箱容量
                                                                      
                table.Rows.Add(r);
            }
            return table;
        }
        VBprinter.EasyReport easyPrint = new VBprinter.EasyReport();
        private bool DoPrint(DataTable dt)
        {
            easyPrint = new VBprinter.EasyReport();
            string currentDir = AppDomain.CurrentDomain.BaseDirectory;
            string configFile = Path.Combine(currentDir + "Template\\", cbTemplate.SelectedValue.ToString()) + ".mb";//路径拼接

            if (File.Exists(configFile))
            {

                easyPrint.SetReportDataSource(dt);
                easyPrint.SetReportFile(configFile);
                easyPrint.PrintReport(false, true, false, false, cbPrint.Text).ToString();

                return true;
            }
            else
            {
                MessageBox.Show("打印模板不存在，请先设计后在打印！");      //未选择模版
                return false;
            }
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tbNumber.Text))
                {
                    MessageBox.Show("请输入容量数", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (cbTemplate.SelectedValue==null || string.IsNullOrWhiteSpace(cbTemplate.SelectedValue.ToString()))
                {
                    MessageBox.Show("打印模板不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                VisitService();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
